package com.yangrd.airship.sys.web.config;

import cn.dev33.satoken.exception.NotLoginException;
import com.yangrd.airship.common.ex.HttpStatusException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;

/**
 * @author yangrd
 * @date 2019/2/20
 **/
@Slf4j
@RequiredArgsConstructor

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        // If the exception is annotated with @ResponseStatus rethrow it and let
        // the framework handle it - like the OrderNotFoundException example
        // at the start of this post.
        // AnnotationUtils is a Spring Framework utility class.
        log.error("uri: {} method: {} exception class: {} exception msg: {}", req.getRequestURI(), req.getMethod(), e.getClass(), e.getMessage());
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        String err = e.getMessage();
        if (e instanceof HttpServerErrorException.InternalServerError) {
            err = ((HttpServerErrorException.InternalServerError) e).getResponseBodyAsString();
        }
        if (e instanceof HttpClientErrorException.Unauthorized | e instanceof NotLoginException) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(err);
        }

        e.printStackTrace();
        // Otherwise setup and send the user to a default error-view.
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(err);
    }

    @ExceptionHandler(value = HttpStatusException.class)
    public ResponseEntity handler(HttpStatusException e){
        return ResponseEntity.status(302).location(URI.create("/error.html?error="+e.getMessage()+"&status="+e.getHttpStatus().value())).build();
    }

}
